package com.oragraph.gui;

import java.util.Enumeration;
import java.util.Vector;

import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;

import com.oragraph.data.Properties;
import com.oragraph.data.PropertiesChangeListener;

public class PropertiesPanel extends JTable {
	
	private Properties _properties;
	private boolean _isMutable;
	private PropertiesPanelModel _model;
	
	public PropertiesPanel(Properties prop, boolean isMutable) {
		super();
		_properties=prop;
		_isMutable=isMutable;
		
		_model=new PropertiesPanelModel(_properties, _isMutable);
		this.setModel(_model);
	}
	
	public void setProperties(Properties prop) {
		_properties=prop;
		_model.setProperties(_properties);
	}

	private class PropertiesPanelModel extends AbstractTableModel implements PropertiesChangeListener {
		
		private Properties _properties;
		private Vector<String> _keys;
		private boolean _isMutable;
		
		public PropertiesPanelModel(Properties prop, boolean isMutable) {
			_properties=prop;
			_isMutable=isMutable;
			_init();
		}
		
		private void _init() {
			if (_properties!=null) {
				_properties.addChangeListener(this);
				Enumeration<String> eKeys=_properties.keys();
				_keys=new Vector<String>();
				while (eKeys.hasMoreElements()) _keys.add(eKeys.nextElement());
			}
			this.fireTableDataChanged();
		}

		public int getColumnCount() {
			return 2;
		}

		@Override
		public int getRowCount() {
			if (_properties!=null) return _keys.size();
			else return 0;
		}

		@Override
		public Object getValueAt(int row, int col) {
			if (_properties==null) return "";
			if (col==0) {
				return _keys.elementAt(row);
			}
			else {
				return _properties.get(_keys.elementAt(row)); 
			}			
		}
		
		public void setProperties(Properties prop) {
			if (_properties!=null) _properties.removeChangeListener(this);
			_properties=prop;
			_init();
		}

		@Override
		public void propertyAdded(Properties properties, String key) {
			_keys.add(key);
			this.fireTableRowsInserted(_keys.size()-1, _keys.size()-1);
		}

		@Override
		public void propertyChanged(Properties properties, String key) {
			int p=-1;
			for (int i=0; i<_keys.size(); i++) {
				if (_keys.elementAt(i).equals(key)) p=i;
			}
			if (p==-1) {
				// TODO ERROR HANDLING
				System.err.println("Could not find key:"+key);
			}
			this.fireTableRowsUpdated(p, p);
		}
		
		public String getColumnName(int col) {
			if (col==0)	return "Key";
			else return "Value";
		}
		
		public boolean isCellEditable(int rowIndex, int columnIndex) {
			if (!_isMutable) return false;
			else {
				if (columnIndex==1) return true;
				else return false;
			}
		}
		
		public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
			if (columnIndex==1) {
				String key=_keys.elementAt(rowIndex);
				_properties.set(key, (String)aValue);
			}
		}
		
		
	}

}
